import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Tree, message, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import { getMenus, createMenu, updateMenu, deleteMenu } from '../../services/api';

const { Option } = Select;
const { TreeNode } = Tree;

const MenuConfig = () => {
  const [menus, setMenus] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [currentMenu, setCurrentMenu] = useState({});
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [treeData, setTreeData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState([]);

  useEffect(() => {
    fetchMenus();
  }, []);

  const fetchMenus = async () => {
    setLoading(true);
    try {
      const data = await getMenus();
      setMenus(data);
      const formattedTreeData = formatTreeData(data);
      setTreeData(formattedTreeData);
      // 默认展开所有节点
      const allKeys = getAllNodeKeys(formattedTreeData);
      setExpandedKeys(allKeys);
    } catch (error) {
      message.error('获取菜单列表失败');
      console.error('Failed to fetch menus:', error);
    }
    setLoading(false);
  };

  // 格式化菜单数据为树结构
  const formatTreeData = (data, parentId = 0) => {
    return data
      .filter(item => item.parentId === parentId)
      .map(item => {
        const children = formatTreeData(data, item.id);
        return {
          title: item.name,
          key: item.id,
          ...item,
          children: children.length > 0 ? children : undefined
        };
      });
  };

  // 获取所有节点的key
  const getAllNodeKeys = (data) => {
    let keys = [];
    data.forEach(node => {
      keys.push(node.key);
      if (node.children) {
        keys = keys.concat(getAllNodeKeys(node.children));
      }
    });
    return keys;
  };

  const handleAdd = () => {
    setEditMode(false);
    setCurrentMenu({});
    form.resetFields();
    setVisible(true);
  };

  const handleEdit = (menu) => {
    setEditMode(true);
    setCurrentMenu(menu);
    form.setFieldsValue(menu);
    setVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deleteMenu(id);
      message.success('删除菜单成功');
      fetchMenus();
    } catch (error) {
      message.error('删除菜单失败');
      console.error('Failed to delete menu:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      if (editMode) {
        await updateMenu(currentMenu.id, values);
        message.success('更新菜单成功');
      } else {
        await createMenu(values);
        message.success('创建菜单成功');
      }
      setVisible(false);
      fetchMenus();
    } catch (error) {
      message.error(editMode ? '更新菜单失败' : '创建菜单失败');
      console.error('Failed to submit menu:', error);
    }
  };

  // 递归渲染树节点
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} dataRef={item} />;
    });

  const filteredMenus = menus.filter(menu =>
    menu.name.toLowerCase().includes(searchText.toLowerCase()) ||
    menu.path.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '菜单名称', dataIndex: 'name', key: 'name' },
    { title: '路径', dataIndex: 'path', key: 'path' },
    { title: '组件', dataIndex: 'component', key: 'component' },
    { title: '图标', dataIndex: 'icon', key: 'icon' },
    { title: '父菜单', dataIndex: 'parentId', key: 'parentId', render: (parentId) => {
      if (parentId === 0) return '无';
      const parentMenu = menus.find(menu => menu.id === parentId);
      return parentMenu ? parentMenu.name : '未知';
    }},
    { title: '排序', dataIndex: 'sort', key: 'sort' },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === 'enabled' ? 'green' : 'red' }}>
        {status === 'enabled' ? '启用' : '禁用'}
      </span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <div>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          style={{ marginRight: 8 }}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Button
          type="danger"
          icon={<DeleteOutlined />}
          size="small"
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      </div>
    )}
  ];

  // 获取所有父菜单选项（排除当前菜单及其子菜单）
  const getParentMenuOptions = () => {
    const excludeIds = editMode ? getAllNodeKeys(formatTreeData([currentMenu])) : [];
    return [
      <Option key={0} value={0}>无</Option>,
      ...menus
        .filter(menu => !excludeIds.includes(menu.id))
        .map(menu => (
          <Option key={menu.id} value={menu.id}>{menu.name}</Option>
        ))
    ];
  };

  return (
    <div className="menu-config">
      <div className="header">
        <h2>菜单配置</h2>
        <div className="search-bar">
          <Input
            placeholder="搜索菜单名称或路径"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增菜单
          </Button>
        </div>
      </div>

      <div className="menu-tree">
        <h3><MenuUnfoldOutlined /> 菜单结构</h3>
        <Tree
          showLine
          defaultExpandAll
          expandedKeys={expandedKeys}
          onExpand={keys => setExpandedKeys(keys)}
          onSelect={([selectedKey]) => {
            const selectedMenu = menus.find(menu => menu.id === Number(selectedKey));
            if (selectedMenu) handleEdit(selectedMenu);
          }}
        >
          {renderTreeNodes(treeData)}
        </Tree>
      </div>

      <Divider />

      <Table
        columns={columns}
        dataSource={filteredMenus}
        loading={loading}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editMode ? '编辑菜单' : '新增菜单'}
        visible={visible}
        onOk={form.submit}
        onCancel={() => setVisible(false)}
        width={600}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="name"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>

          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: '请输入路径' }]}
          >
            <Input placeholder="请输入路径" />
          </Form.Item>

          <Form.Item name="component" label="组件路径">
            <Input placeholder="请输入组件路径" />
          </Form.Item>

          <Form.Item name="icon" label="图标">
            <Input placeholder="请输入图标名称" />
          </Form.Item>

          <Form.Item name="parentId" label="父菜单">
            <Select placeholder="请选择父菜单">
              {getParentMenuOptions()}
            </Select>
          </Form.Item>

          <Form.Item name="sort" label="排序">
            <Input type="number" placeholder="请输入排序号" />
          </Form.Item>

          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="enabled">启用</Option>
              <Option value="disabled">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuConfig;